/**
 * 
 */
package br.webcrawler.activities.parser;

import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

/**
 * @author Gerson Groth
 * 
 */
public class XmlParser {

//	 private static final String XML_PATH = "C:\\Users\\Gerson\\Desktop\\São Silvestre 2012\\Xml";
	private static final String XML_PATH = "C:\\Users\\Gerson\\Desktop\\garminConnect\\xml";

	public static void main(String[] args) {
		parser(XML_PATH);
	}

	public static void parser(String path) {
		SAXBuilder builder = new SAXBuilder();
		File xmlFolder = new File(path);
		File[] xmlFile = xmlFolder.listFiles();

		Map<String, Integer> activityTypeMap = new HashMap<String, Integer>();
		int contador = 0;

		for (File f : xmlFile) {
			try {
				if (!f.getName().startsWith("activity_"))
					continue;

				Document document = (Document) builder.build(f);
				Element activity = document.getRootElement();

				Element headerContent = getElement(activity, "HeaderContent");
				Element activityName = getElement(headerContent, "ActivityName");
				Element timestamp = getElement(headerContent, "Timestamp");
				Element userName = getElement(headerContent, "UserName");
				Element activityType = getElement(headerContent, "ActivityType");
				if (activityTypeMap.containsKey(activityType.getText().trim())) {
					activityTypeMap.put(
							activityType.getText().trim(),
							new Integer(activityTypeMap.get(activityType
									.getText()) + 1));
				} else {
					activityTypeMap.put(activityType.getText().trim(),
							new Integer(1));
				}

				Element eventType = getElement(headerContent, "EventType");
				Element course = getElement(headerContent, "Course");

				Element summary = getElement(activity, "Summary");
				Element summaryDistance = getElement(activity, "Distance");
				Element summaryTime = getElement(activity, "Time");
				Element summaryAvgPace = getElement(activity, "AvgPace");
				Element summaryAvgSpeed = getElement(activity, "AvgSpeed");
				Element summaryElevationGain = getElement(activity,
						"ElevationGain");
				Element summaryCalories = getElement(activity, "Calories");

				Element details = getElement(activity, "Details");

				Element timing = getElement(details, "Timing");
				Element timingTime = getElement(timing, "Time");
				Element timingMovingTime = getElement(timing, "MovingTime");
				Element timingElapsedTime = getElement(timing, "ElapsedTime");
				Element timingAvgSpeed = getElement(timing, "AvgSpeed");
				Element timingAvgMovingSpeed = getElement(timing,
						"AvgMovingSpeed");
				Element timingMaxSpeed = getElement(timing, "MaxSpeed");
				Element timingAvgPace = getElement(timing, "AvgPace");
				Element timingAvgMovingPace = getElement(timing,
						"AvgMovingPace");
				Element timingBestPace = getElement(timing, "BestPace");

				Element elevation = getElement(details, "Elevation");
				Element elevationGain = getElement(elevation, "ElevationGain");
				Element elevationLoss = getElement(elevation, "ElevationLoss");
				Element minElevation = getElement(elevation, "MinElevation");
				Element maxElevation = getElement(elevation, "MaxElevation");

				Element heartRate = getElement(details, "HeartRate");
				Element heartRateAvgHRbpm = getElement(heartRate, "AvgHRbpm");
				Element heartRateMaxHRbpm = getElement(heartRate, "MaxHRbpm");
				Element heartRateTrainingEffectbpm = getElement(heartRate, "TrainingEffectbpm");
				Element heartRateAvgHRPercent = getElement(heartRate, "AvgHRPercent");
				Element heartRateMaxHRPercent = getElement(heartRate, "MaxHRPercent");
				Element heartRateTrainingEffectPercent = getElement(heartRate, "TrainingEffectPercent");
				Element heartRateAvgHRZones = getElement(heartRate, "AvgHRZones");
				Element heartRateMaxHRZones = getElement(heartRate, "MaxHRZones");
				Element heartRateTrainingEffectZones = getElement(heartRate, "TrainingEffectZones");
				if(heartRateAvgHRbpm == null){
					contador++;
				}

				Element cadence = getElement(details, "Cadence");
				Element avgRunCadence = getElement(cadence, "AvgRunCadence");
				Element maxRunCadence = getElement(cadence, "MaxRunCadence");

				Element laps = getElement(activity, "Laps");
				List<Element> lap = laps.getChildren();

				Element weather = activity.getChild("Weather");

				Element additionalInfo = activity.getChild("AdditionalInfo");

				// TODO - criar interface para definir regras que gerem a
				// estatística...

				// MAP<String, Integer> - chave é o valor do xml (running, por
				// exemplo) e o valor é o número (qtde)
			} catch (Exception e) {
				System.err.println(e.getMessage());
			}

		}
		
		Set s = activityTypeMap.entrySet();
		// Move next key and value of Map by iterator
		Iterator it = s.iterator();
	
		while (it.hasNext()) {
			// key=value separator this by Map.Entry to get key and value
			Map.Entry m = (Map.Entry) it.next();

			// getKey is used to get key of Map
			String key = (String) m.getKey();

			// getValue is used to get value of key in Map
			Integer value = (Integer) m.getValue();

			System.out.println(key+": " + value);
		}
		System.out.println("Corridas com batimento cardíaco: " + contador);

	}

	private static Element getElement(Element element, String child) {
		if (element == null)
			return null;

		Element eChild = element.getChild(child);
		if (eChild == null)
			return null;

//		System.out.println(eChild.getName() + " -> " + eChild.getText());
		return eChild;
	}
}
